<template>
  <div class="purposeTable">
    <t-card class="card-container" :bordered="false">
      <t-row justify="space-between">
          <div class="left-operation-container">
            <t-input v-model="searchValue" placeholder="请输入名称或备注" clearable style="display: inline-block; margin-right: 30px;">
            </t-input>
            <t-button theme="primary">
              <search-icon size="16px" />
              查询
            </t-button>
            <t-button variant="outline" theme="primary">
              <refresh-icon size="16px" />
              刷新
            </t-button>
          </div>
          <div class="right-operation-container">
            <t-button>新增</t-button>
            <t-button variant="base" theme="default">导入</t-button>
            <t-button variant="base" theme="default">导出</t-button>
          </div>
      </t-row>
      <t-table
        ref="tableRef"
        row-key="key"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        :editable-row-keys.sync="editableRowKeys"
        lazyLoad
        @row-edit="onRowEdit"
        @row-validate="onRowValidate"
        @validate="onValidate"
        @change="onChange"
        @page-change="onPageChange"
        @select-change="onSelectChange"
      />
    </t-card>
  </div>
</template>

<script setup lang="tsx">
import { SearchIcon, RefreshIcon } from 'tdesign-icons-vue-next';
import { ref, reactive, computed } from 'vue';
import {
  Input, Select, MessagePlugin
} from 'tdesign-vue-next';

const initData: Array<object> = new Array(21).fill(null).map((_, i) => ({
  key: String(i + 1),
  rowSelect: [true, false][i % 2],
  projectName: ['限时优惠', '国庆黄金周', '冬令营'][i % 3],
  priorityLevel: ['低', '中', '高'][i % 3],
  protectLevel: ['低', '中', '高'][i % 3],
  targetRange: ['卫星目标', '空中目标', '水面目标', '水下目标', '固定设施', '陆地目标' ][i % 6],
  targetType: ['战斗机', '预警机', '无人机', '地面雷达', '水面舰艇', '潜艇', '卫星'][i % 7],
  country: ['中国', '美国', '英国', '法国', '德国', '日本', '俄罗斯', '印度', '加拿大', '澳大利亚'][i % 10],
  remark: ['今天天晴', '今天有雾霾，减少外出', '今天多云', '今天多云', '今天多云', '今天多云', '今天多云', '今天多云', '今天多云', '今天多云'][i % 10]
}));

// const initData1: Array<object> = [
//   {
//     key: 'id1',
//     rowSelect: true,
//     projectName: '限时优惠',
//     priorityLevel: '高',
//     protectLevel: '高',
//     targetRange: '卫星目标',
//     targetType: '战斗机',
//     country: '中国',
//     remark: '今天天晴'
//   },
//   {
//     key: 'id2',
//     rowSelect: true,
//     projectName: '国庆黄金周',
//     priorityLevel: '高',
//     protectLevel: '高',
//     targetRange: '空中目标',
//     targetType: '预警机',
//     country: '中国',
//     remark: '今天有雾霾，减少外出'
//   },
//   {
//     key: 'id3',
//     rowSelect: true,
//     projectName: '冬令营',
//     priorityLevel: '高',
//     protectLevel: '高',
//     targetRange: '空中目标',
//     targetType: '战斗机',
//     country: '中国',
//     remark: '今天多云'
//   },
// ];
const STATUS_OPTIONS = [
  {
    label: '小',
    value: 0,
  },
  {
    label: '中',
    value: 1,
  },
  {
    label: '高',
    value: 2,
  },
];
const TARGET_OPTIONS = [
  {
    label: '空中目标',
    value: 0,
  },
  {
    label: '水面目标',
    value: 1,
  },
  {
    label: '陆地目标',
    value: 2,
  },
  {
    label: '卫星目标',
    value: 3,
  }
];
const COUNTRY_OPTIONS = [
  {
    label: '中国',
    value: 0
  },
  {
    label: '美国',
    value: 1
  },
  {
    label: '俄罗斯',
    value: 2
  },
  {
    label: '英国',
    value: 3
  }
];
const TOTAL = 21;
const pagination = reactive({
  current: 1,
  pageSize: 5,
  total: TOTAL,
  showJumper: true,
});
const tableRef = ref();
const align = ref('left');
const data = ref([...initData]);
const editableRowKeys = ref([]);
const currentSaveId = ref('');
const searchValue = ref('');
// 保存变化过的行信息
const editMap = reactive({});
const onCancel = (e: any) => {
  const { id } = e.currentTarget.dataset;
  updateEditState(id);
  tableRef.value.clearValidateData();
};
const columns = computed(() => [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 60,
    fixed: 'left',
  },
  {
    title: '项目名称',
    colKey: 'projectName',
    width: 120,
    fixed: 'left',
    align: align.value,
    edit: {
      component: Input,
      showEditIcon: false
    }
  },
  {
    title: '优先等级',
    colKey: 'priorityLevel',
    width: 120,
    align: align.value,
    // 编辑状态相关配置，全部集中在 edit
    edit: {
      // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
      // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
      component: Select,
      // props, 透传全部属性到 Input 组件
      props: {
        clearable: true,
        // autofocus: true,
        options: STATUS_OPTIONS
      },
      // 校验规则，此处同 Form 表单
      rules: [
        {
          required: true,
          message: '不能为空',
        },
        // {
        //   max: 10,
        //   message: '字符数量不能超过 10',
        //   type: 'warning',
        // },
      ],
      showEditIcon: false,
    },
  },
  {
    title: '防护等级',
    colKey: 'protectLevel',
    width: 120,
    align: align.value,
    edit: {
      component: Select,
      // props, 透传全部属性到 Select 组件
      props: {
        clearable: true,
        options: STATUS_OPTIONS,
      },
      // 校验规则，此处同 Form 表单
      rules: [
        {
          required: true,
          message: '不能为空',
        },
      ],
      showEditIcon: false,
      // on: ({ updateEditedCellValue }) => ({
        // onChange: () => {
          /**
           * change other columns edited cell value
           * 更新本行其他编辑态单元格的数据(to update editedRow)
           */
          // updateEditedCellValue({
            // isUpdateCurrentRow: true,
            // letters: [],
            // 'user.firstName': '',
            // createTime: dayjs().add(1, 'day').toDate(),
          // });
          /**
           * update edited row data with row unique value is qual to 2
           * 更新行唯一标识值为 2 的编辑态数据
           */
          // updateEditedCellValue({ rowValue: 2, letters: [] });
        // },
      // }),
    },
  },
  {
    title: '目标范围',
    colKey: 'targetRange',
    width: 120,
    align: align.value,
    edit: {
      component: Select,
      showEditIcon: false,
      props: {
        clearable: true,
        options: TARGET_OPTIONS
      }
    }
  },
  {
    title: '目标类型',
    colKey: 'targetType',
    width: 120,
    align: align.value,
    edit: {
      component: Select,
      showEditIcon: false,
      props: {
        clearable: true,
        options: TARGET_OPTIONS
      }
    }
  },
  {
    title: '国家',
    colKey: 'country',
    width: 120,
    align: align.value,
    edit: {
      component: Select,
      showEditIcon: false,
      props: {
        clearable: true,
        options: COUNTRY_OPTIONS
      }
    }
  },
  {
    title: '备注',
    colKey: 'remark',
    width: 200,
    align: align.value,
    edit: {
      component: Input,
      showEditIcon: false,
      props: {
        clearable: true,
        placeholder: '请输入备注'
      }
    }
  },
  {
    title: '操作栏',
    colKey: 'operate',
    width: 150,
    cell: (h, { row }) => {
      const editable = editableRowKeys.value.includes(row.key);
      return (
        <div class="table-operations">
          {!editable && (
            <t-link theme="primary" hover="color" data-id={row.key} onClick={onEdit}>
              修改
            </t-link>
          )}
          {editable && (
            <t-link theme="primary" hover="color" data-id={row.key} onClick={onSave}>
              确定
            </t-link>
          )}
          {editable && (
            <t-link theme="primary" hover="color" data-id={row.key} onClick={onCancel}>
              取消
            </t-link>
          )}
          {(
            <t-link theme="primary" hover="color" data-id={row.key}>
              删除
            </t-link>
          )}
        </div>
      );
    },
  },
]);
const onEdit = (e: any) => {
  const { id } = e.currentTarget.dataset;
  console.log('-onEdit-', id);
  if (!editableRowKeys.value.includes(id)) {
    editableRowKeys.value.push(id);
  }
};
const updateEditState = (id: number) => {
  const index = editableRowKeys.value.findIndex((t) => t === id);
  editableRowKeys.value.splice(index, 1);
};
const onSave = (e: any) => {
  const { id } = e.currentTarget.dataset;
  currentSaveId.value = id;
  // 触发内部校验，而后在 onRowValidate 中接收异步校验结果
  // 重点：受框架层面限制，如果是 EnhancedTable 请更为使用 this.$refs.tableRef.primaryTableRef.validateRowData(id)
  // this.$refs.tableRef.primaryTableRef.validateRowData(id).then((params) => {
  tableRef.value.validateRowData(id).then((params: any) => {
    console.log('Event Table Promise Validate:', params);
    if (params.result.length) {
      const r = params.result[0];
      MessagePlugin.error(`${r.col.title} ${r.errorList[0].message}`);
      return;
    }
    // 如果是 table 的父组件主动触发校验
    if (params.trigger === 'parent' && !params.result.length) {
      const current = editMap[currentSaveId.value];
      if (current) {
        data.value.splice(current.rowIndex, 1, current.editedRow);
        MessagePlugin.success('保存成功');
      }
      updateEditState(currentSaveId.value);
    }
  });
};
// 行校验反馈事件，this.$refs.tableRef.validateRowData 执行结束后触发
const onRowValidate = (params: any) => {
  console.log('Event Table Row Validate:', params);
};
const onValidateTableData = () => {
  // 执行结束后触发事件 validate
  tableRef.value.validateTableData().then((params: any) => {
    console.log('Promise Table Data Validate:', params);
    const cellKeys = Object.keys(params.result);
    const firstError = params.result[cellKeys[0]];
    if (firstError) {
      MessagePlugin.warning(firstError[0].message);
    }
  });
};
// 表格全量数据校验反馈事件，this.$refs.tableRef.validateTableData() 执行结束后触发
const onValidate = (params: any) => {
  console.log('Event Table Data Validate:', params);
};
const onRowEdit = (params: any) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const {
    row,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    rowIndex,
    col,
    value,
  } = params;
  const oldRowData = editMap[row.key]?.editedRow || row;
  const editedRow = {
    ...oldRowData,
    [col.colKey]: value,
  };
  editMap[row.key] = {
    ...params,
    editedRow,
  };

  // ⚠️ 重要：以下内容应用于全量数据校验（单独的行校验不需要）
  // const newData = [...this.data];
  // newData[rowIndex] = editedRow;
  // this.data = newData;
  // 或者
  // this.$set(this.data, rowIndex, editedRow);
};
  // 分页、排序、过滤等操作触发均会触发 change 事件
const onChange = (params: any, context: any) => {
  console.log('change:', params, context);
};
// 分页变化时触发该事件
const onPageChange = (pageInfo: any, newData: any) => {
    pagination.current = pageInfo.current;
    pagination.pageSize = pageInfo.pageSize;
   console.log('page-change:', pageInfo, newData);
};
// 选中行发生变化时触发，泛型 T 指表格数据类型
const onSelectChange = (selectedRowKeys: any, context: any) => {
  console.log(selectedRowKeys, context);
};
</script>

<style>
.purposeTable .table-operations > .t-link {
  margin-right: 8px;
}
.purposeTable .t-demo-col__datepicker .t-date-picker {
  width: 120px;
}
</style>
